package com.wy.component.wxUtils;

import java.awt.Menu;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import net.sf.json.JSONObject;


/**
 * @author zhusw
 * @description TODO(请求数据通用类)
 * 2016年2月26日 下午10:46:55
 */
public class WeixinUtil {
	
	/**
	 * qyTokenMap:企业号token工厂
	 * @since Ver 1.1
	 */
	private static Map qyTokenMap = new HashMap();
	
    /** 
     * 发起https请求并获取结果 
     *  
     * @param requestUrl 请求地址 
     * @param requestMethod 请求方式（GET、POST） 
     * @param outputStr 提交的数据 
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值) 
     */  
	public static JSONObject HttpRequest(String request , String RequestMethod , String output ){
		@SuppressWarnings("unused")
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		try {
			//建立连接
			URL url = new URL(request);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod(RequestMethod);
			if(output!=null){
				OutputStream out = connection.getOutputStream();
				out.write(output.getBytes("UTF-8"));
				out.close();
			}
			//流处理
			InputStream input = connection.getInputStream();
			InputStreamReader inputReader = new InputStreamReader(input,"UTF-8");
			BufferedReader reader = new BufferedReader(inputReader);
			String line;
			while((line=reader.readLine())!=null){
				buffer.append(line);
			}
			//关闭连接、释放资源
			reader.close();
			inputReader.close();
			input.close();
			input = null;
			connection.disconnect();
			jsonObject = JSONObject.fromObject(buffer.toString());
		} catch (Exception e) {
		}
		return jsonObject;
	} 
//	 获取access_token的接口地址（GET）   
	public final static String access_token_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=CorpID&corpsecret=SECRET";  

	/** 
	 * 获取access_token 
	 *  
	 * @param CorpID 企业Id 
	 * @param SECRET 管理组的凭证密钥，每个secret代表了对应用、通讯录、接口的不同权限；不同的管理组拥有不同的secret 
	 * @return 
	 */  
	public static AccessToken getAccessToken(String corpID, String secret) {
	    AccessToken accessToken = null;  
	    //从工厂取得token和末次获取时间
		String token = (String) qyTokenMap.get("token");
//		System.out.println("--------------------"+token);
		Date addTokenTime = (Date) qyTokenMap.get("addTokenTime");
		if (token != null && !"".equals(token)) {
			// 判断有效时间 是否超过2小时
			Date end = new Date();
//			System.out.println("--------------------"+formatDateStr(addTokenTime, "yyyy-MM-dd HH:mm"));
			if ((end.getTime() - addTokenTime.getTime()) / 1000 / 3600 >= 2) {
				// 失效 重新获取
				accessToken = reFetchToken(corpID,secret);
			} 
			else {
	            accessToken = new AccessToken();  
	            accessToken.setToken(token);  
				return accessToken;
			}
		} else {
			accessToken = reFetchToken(corpID,secret);
		}
	    return accessToken;  
	}
	
	
	/** 
	 * 获取access_token 
	 *  
	 * @param CorpID 企业Id 
	 * @param SECRET 管理组的凭证密钥，每个secret代表了对应用、通讯录、接口的不同权限；不同的管理组拥有不同的secret 
	 * @return 
	 */  
	public static AccessToken getAccessTokenChat(String corpID, String secret) {
	    AccessToken accessToken = null;  
	    //从工厂取得token和末次获取时间
		String token = (String) qyTokenMap.get("tokenChat");
//		System.out.println("--------------------"+token);
		Date addTokenTime = (Date) qyTokenMap.get("addTokenTimeChat");
		if (token != null && !"".equals(token)) {
			// 判断有效时间 是否超过2小时
			Date end = new Date();
//			System.out.println("--------------------"+formatDateStr(addTokenTime, "yyyy-MM-dd HH:mm"));
			if ((end.getTime() - addTokenTime.getTime()) / 1000 / 3600 >= 2) {
				// 失效 重新获取
				accessToken = reFetchTokenChat(corpID,secret);
			} 
			else {
	            accessToken = new AccessToken();  
	            accessToken.setToken(token);  
				return accessToken;
			}
		} else {
			accessToken = reFetchTokenChat(corpID,secret);
		}
	    return accessToken;  
	}
	
	public static String formatDateStr(Date date,String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format,Locale.US); 
		try {
			return sdf.format(date); 
		} catch (Exception e) {
			System.err.println("Exception caught: " + e.getMessage());
		}
		return null;
	}
	
	private static AccessToken reFetchToken(String corpID, String secret) {
	    String requestUrl = access_token_url.replace("CorpID", corpID).replace("SECRET", secret);  
	    JSONObject jsonObject = HttpRequest(requestUrl, "GET", null);  
	    AccessToken accessToken = null;
	    // 如果请求成功  
	    if (null != jsonObject) {  
	        try {  
	        	accessToken = new AccessToken();  
	            accessToken.setToken(jsonObject.getString("access_token"));  
	            accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
	            qyTokenMap.put("token", accessToken.getToken());
	            qyTokenMap.put("addTokenTime", new Date());
	            System.out.println("获取token成功:"+jsonObject.getString("access_token")+"————"+jsonObject.getInt("expires_in"));
	        } catch (Exception e) {  
	            accessToken = null;  
	            // 获取token失败  
	            String error = String.format("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));  
	            System.out.println(error);
	        }  
	    }
	    return accessToken;
	}
	
	private static AccessToken reFetchTokenChat(String corpID, String secret) {
	    String requestUrl = access_token_url.replace("CorpID", corpID).replace("SECRET", secret);  
	    JSONObject jsonObject = HttpRequest(requestUrl, "GET", null);  
	    AccessToken accessToken = null;
	    // 如果请求成功  
	    if (null != jsonObject) {  
	        try {  
	        	accessToken = new AccessToken();  
	            accessToken.setToken(jsonObject.getString("access_token"));  
	            accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
	            qyTokenMap.put("tokenChat", accessToken.getToken());
	            qyTokenMap.put("addTokenTimeChat", new Date());
	            System.out.println("获取token成功:"+jsonObject.getString("access_token")+"————"+jsonObject.getInt("expires_in"));
	        } catch (Exception e) {  
	            accessToken = null;  
	            // 获取token失败  
	            String error = String.format("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));  
	            System.out.println(error);
	        }  
	    }
	    return accessToken;
	}
	
	//	 菜单创建（POST）   
	public static String menu_create_url = "https://qyapi.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN&agentid=1";  
	  
	/** 
	 * 创建菜单 
	 *  
	 * @param menu 菜单实例 
	 * @param accessToken 有效的access_token 
	 * @param agentid  企业应用的id，整型，可在应用的设置页面查看
	 * @return 0表示成功，其他值表示失败 
	 */  
	public static int createMenu(Menu menu, String accessToken) {  
	    int result = 0;  
	  
	    // 拼装创建菜单的url  
	    String url = menu_create_url.replace("ACCESS_TOKEN", accessToken);  
	    // 将菜单对象转换成json字符串  
	    String jsonMenu = JSONObject.fromObject(menu).toString();  
	    // 调用接口创建菜单  
	    JSONObject jsonObject = HttpRequest(url, "POST", jsonMenu);  
	  
	    if (null != jsonObject) {  
	        if (0 != jsonObject.getInt("errcode")) {  
	            result = jsonObject.getInt("errcode");  
	            String error = String.format("创建菜单失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));  
	            System.out.println(error); 
	        }  
	    }  
	  
	    return result;  
	}  
	public static String URLEncoder(String str){
		String result = str ;
		try {
		result = java.net.URLEncoder.encode(result,"UTF-8");	
		} catch (Exception e) {
        e.printStackTrace();
		}
		return result;
	}
	/**
	 * 根据内容类型判断文件扩展名
	 * 
	 * @param contentType 内容类型
	 * @return
	 */
	public static String getFileEndWitsh(String contentType) {
		String fileEndWitsh = "";
		if ("image/jpeg".equals(contentType))
			fileEndWitsh = ".jpg";
		else if ("audio/mpeg".equals(contentType))
			fileEndWitsh = ".mp3";
		else if ("audio/amr".equals(contentType))
			fileEndWitsh = ".amr";
		else if ("video/mp4".equals(contentType))
			fileEndWitsh = ".mp4";
		else if ("video/mpeg4".equals(contentType))
			fileEndWitsh = ".mp4";
		return fileEndWitsh;
	}
	/**
	 * 数据提交与请求通用方法
	 * @param access_token 凭证
	 * @param RequestMt 请求方式
	 * @param RequestURL 请求地址
	 * @param outstr 提交json数据
	 * */
    public static int PostMessage(String access_token ,String RequestMt , String RequestURL , String outstr){
    	int result = 0;
    	RequestURL = RequestURL.replace("ACCESS_TOKEN", access_token);
    	System.out.println("2==="+outstr);
    	JSONObject jsonobject = WeixinUtil.HttpRequest(RequestURL, RequestMt, outstr);
    	System.out.println(jsonobject);
//    	Iterator iterator = jsonobject.keys();
//    	while(iterator.hasNext()){
//        	String key = (String) iterator.next();
//	        String value = jsonobject.getString(key);
//		}
    	 if (null != jsonobject) {  
 	        if (0 != jsonobject.getInt("errcode")) {  
 	            result = jsonobject.getInt("errcode");  
 	            String error = String.format("操作失败 errcode:{} errmsg:{}", jsonobject.getInt("errcode"), jsonobject.getString("errmsg"));  
 	            System.out.println(error); 
 	        }  
 	    }
    	return result;
    }
    
	/**
	 * Function Name               syncUserToQyhByMobile                                   
	 * @param USERID
	 * @param USERNAME
	 * @param QYORGID
	 * @param JOBPOSITION
	 * @param GENDER
	 * @param mobile          		             
	 * @description 人员同步到企业号mobile
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-5-23 下午3:58:00             黄忠                     Initial
	 **********************************************************************
	 */
	public static void syncUserToQyhByMobile(String USERID,String USERNAME,String QYORGID,String JOBPOSITION,String GENDER,String mobile,String email ) {
		String access_token = WeixinUtil.getAccessToken(new ParamesAPI().getCorpId(), new ParamesAPI().getSecret()).getToken();
		String postJson = MPerson.create(USERID, USERNAME,"["+QYORGID+"]",JOBPOSITION, mobile, GENDER, mobile, email , "");
		WeixinUtil.PostMessage(access_token, "POST", MPerson.CREATE_URL, postJson);
	}
	
	/**
	 * 
	 * Function Name               syncUserUpdate                                   
	 * @param USERID
	 * @param USERNAME
	 * @param QYORGID
	 * @param JOBPOSITION
	 * @param GENDER
	 * @param mobile          		             
	 * @description 跟新人员到企业号
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-6-6 下午8:46:23           黄忠                     Initial
	 **********************************************************************
	 */
	public static void syncUserUpdate(String USERID,String USERNAME,String QYORGID,String JOBPOSITION,String GENDER,String mobile,String emall) {
		String access_token = WeixinUtil.getAccessToken(new ParamesAPI().getCorpId(), new ParamesAPI().getSecret()).getToken();
		String postJson = MPerson.update(USERID, USERNAME, QYORGID, JOBPOSITION, mobile, "0", "",emall, "", "1");
		WeixinUtil.PostMessage(access_token, "POST", MPerson.UPDATA_URL, postJson);
	}
}  
